package route

import (
	"log"
	"net/http"
	"strings"
)

type Mux struct {
	handlers map[string][]*Handler
	NotFound http.HandlerFunc
	static   string
}

type Handler struct {
	path string
	http.HandlerFunc
}

func New(static string, NotFound http.HandlerFunc) *Mux {
	return &Mux{make(map[string][]*Handler), NotFound, static}
}

//开启http服务
func (m *Mux) Listen(port string) {
	err := http.ListenAndServe(port, m)
	if err != nil {
		log.Fatal("开启http服务错误!")
	}
}

//添加路由
func (m *Mux) add(mode, path string, fun http.HandlerFunc) {
	h := &Handler{
		strings.ToLower(path),
		fun}
	m.handlers[strings.ToLower(mode)] = append(
		m.handlers[strings.ToLower(mode)],
		h,
	)
}

//添加路由
func (m *Mux) AddRoute(mode string, path string, fun http.HandlerFunc) {
	m.add(mode, path, fun)
}

//设置404执行函数
func (this *Mux) SetNotFound(fun http.HandlerFunc) {
	this.NotFound = fun
}

//进行路由分配
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//例如：127.0.0.1:8080/a/a  = a/a
	url := strings.Split(strings.TrimLeft(r.URL.Path, "/"), "/")
	if strings.ToLower(url[0]) == strings.ToLower(m.static) { //处理静态文件
		http.ServeFile(w, r, "."+r.URL.Path)
		return
	}
	log.Printf("url[x] = %s", url[0])
	log.Printf("m.static = %s", m.static)
	log.Printf("r.Method = %s", r.Method)
	//获取基本请求方式 get post pull 等等
	for _, handler := range m.handlers[strings.ToLower(r.Method)] {
		if handler.path == "/"+strings.ToLower(url[0]) { //处理http method
			handler.ServeHTTP(w, r)
			return
		}
	}
	if m.NotFound != nil {
		w.WriteHeader(404)
		m.NotFound.ServeHTTP(w, r)
		return
	}
	http.NotFound(w, r)
}
